﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using EzFrameWork;
using LitJson;
using UnityEngine;
using UnityEngine.Networking;

public class WeatherID {

    static Dictionary<string, string> dicweatherData = new Dictionary<string, string> ();
    static bool isReadData = false;
    private static string weatherID;
    private static void ReadCNWeatherIDTXT () {
        weatherID = Resources.Load<TextAsset> ("CNWeatherID").text;
        string[] weatherItems = weatherID.Split (',');
        for (int i = 0; i < weatherItems.Length; i++) {
            string CityName = "";
            string CityID = "";
            string[] items = weatherItems[i].Split (':');
            if (items.Length == 2) {
                string[] sName = items[0].Split ('\"');
                CityName = sName[1];
                string[] sID = items[1].Split ('\"');
                CityID = sID[1];
            }
            if (CityName != "" && CityID != "") {

                if (!dicweatherData.ContainsKey (CityName)) {
                    dicweatherData.Add (CityName, CityID);
                }
            }
        }
        isReadData = true;
    }

    public static string GetWeatherID (string CityName) {

        if (!isReadData) {
            ReadCNWeatherIDTXT ();
        }
        string ID = "";
        if (dicweatherData.ContainsKey (CityName)) {
            ID = dicweatherData[CityName];
        } else {
            Debug.Log ("城市名输入错误");
        }
        return ID;
    }

    /// <summary>
    /// 所有的城市
    /// </summary>
    /// <returns></returns>
    public static List<string> AllCity () {

        List<string> ListCity = new List<string> ();
        foreach (var item in dicweatherData) {
            ListCity.Add (item.Key);
        }
        return ListCity;
    }
}

public class Weather {
    private static string weatherInfoUrl = "http://wthrcdn.etouch.cn/WeatherApi?citykey=";
    public static WeatherData CreateWeatherData (string CityID) {
        string URL = "http://wthrcdn.etouch.cn/WeatherApi?citykey=" + CityID;
        XmlDocument document = new XmlDocument ();
        WeatherData weatherData = new WeatherData ();
        document.LoadXml (GetHtml (URL));
        weatherData.CityName = document.SelectSingleNode ("resp").SelectSingleNode ("city").InnerText;
        weatherData.TemperatureNow = document.SelectSingleNode ("resp").SelectSingleNode ("wendu").InnerText;
        weatherData.Day = document.SelectSingleNode ("resp").SelectSingleNode ("forecast").SelectSingleNode ("weather").SelectSingleNode ("date").InnerText;
        weatherData.TemperatureMax = document.SelectSingleNode ("resp").SelectSingleNode ("forecast").SelectSingleNode ("weather").SelectSingleNode ("high").InnerText;
        weatherData.TemperatureMin = document.SelectSingleNode ("resp").SelectSingleNode ("forecast").SelectSingleNode ("weather").SelectSingleNode ("low").InnerText;
        weatherData.DayWeather = document.SelectSingleNode ("resp").SelectSingleNode ("forecast").SelectSingleNode ("weather").SelectSingleNode ("day").SelectSingleNode ("type").InnerText;
        weatherData.DayWind = document.SelectSingleNode ("resp").SelectSingleNode ("forecast").SelectSingleNode ("weather").SelectSingleNode ("day").SelectSingleNode ("fengxiang").InnerText;
        weatherData.DayWindLevel = document.SelectSingleNode ("resp").SelectSingleNode ("forecast").SelectSingleNode ("weather").SelectSingleNode ("day").SelectSingleNode ("fengli").InnerText;
        weatherData.NightWeather = document.SelectSingleNode ("resp").SelectSingleNode ("forecast").SelectSingleNode ("weather").SelectSingleNode ("night").SelectSingleNode ("type").InnerText;
        weatherData.NightWind = document.SelectSingleNode ("resp").SelectSingleNode ("forecast").SelectSingleNode ("weather").SelectSingleNode ("night").SelectSingleNode ("fengxiang").InnerText;
        weatherData.NightWindLevel = document.SelectSingleNode ("resp").SelectSingleNode ("forecast").SelectSingleNode ("weather").SelectSingleNode ("night").SelectSingleNode ("fengli").InnerText;
        return weatherData;
    }

    private static string GetHtml (string url) {
        float a = Time.time;
        StringBuilder s = new StringBuilder (102400);
        HttpWebRequest wr = (HttpWebRequest) WebRequest.Create (url);
        wr.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
        HttpWebResponse response = (HttpWebResponse) wr.GetResponse ();
        GZipStream g = new GZipStream (response.GetResponseStream (), CompressionMode.Decompress);
        byte[] d = new byte[20480];
        int l = g.Read (d, 0, 20480);
        while (l > 0) {
            s.Append (Encoding.UTF8.GetString (d, 0, l));
            l = g.Read (d, 0, 20480);
        }
        float temp = Time.time - a;
        return s.ToString ();
    }
        
    /// <summary>
    /// 第二种获取天气的方法
    /// </summary>
    /// <param name="WeatherID"></param>
    /// <param name="action"></param>
    public static void GetWeather (string WeatherID, Action<RootWeather> action) {
        EzMonoManager.Instance.StartCoroutine (GetText (WeatherID, action));
    }

    static IEnumerator GetText (string WeatherID, Action<RootWeather> action) {
        UnityWebRequest www = UnityWebRequest.Get ("http://www.weather.com.cn/data/sk/" + WeatherID + ".html");
        yield return www.SendWebRequest ();
        if (www.isNetworkError || www.isHttpError) {
            Debug.Log (www.error);
        } else {
            RootWeather rootWeather = JsonMapper.ToObject<RootWeather> (www.downloadHandler.text);
            action (rootWeather);
        }
    }

    private void IniWeatherData (string s) {
        
    }
}

public class WeatherData {

    private string cityName;
    private string day; //日期

    /// <summary>
    /// 城市
    /// </summary>
    /// <value></value>
    public string CityName {
        set { cityName = value; }
        get { return cityName; }
    }

    /// <summary>
    /// 日期
    /// </summary>
    /// <value></value>
    public string Day {
        set { day = value; }
        get { return day; }
    }

    private string temperatureNow;

    /// <summary>
    /// 当前温度
    /// </summary>
    /// <value></value>
    public string TemperatureNow {
        set { temperatureNow = value; }
        get { return temperatureNow; }
    }

    private string temperatureMax; //气温

    /// <summary>
    /// 
    /// </summary>
    /// <value></value>
    public string TemperatureMax {
        set { temperatureMax = value; }
        get { return temperatureMax; }
    }

    public string temperatureMin;
    public string TemperatureMin {
        set { temperatureMin = value; }
        get { return temperatureMin; }
    }

    public string dayWeather; //白天天气
    public string DayWeather {
        set { dayWeather = value; }
        get { return dayWeather; }
    }

    public string dayWind; //白天风向
    public string DayWind {
        set { dayWind = value; }
        get { return dayWind; }
    }

    public string dayWindLevel; //白天风力
    public string DayWindLevel {
        set { dayWindLevel = value; }
        get { return dayWindLevel; }
    }

    public string nightWeather; //夜晚天气
    public string NightWeather {
        set { nightWeather = value; }
        get { return nightWeather; }
    }

    public string nightWind; //夜晚风向
    public string NightWind {
        set { nightWind = value; }
        get { return nightWind; }
    }

    public string nightWindLevel; //夜晚风力
    public string NightWindLevel {
        set { nightWindLevel = value; }
        get { return nightWindLevel; }
    }

    private string weatherInfoUrl = "http://wthrcdn.etouch.cn/WeatherApi?citykey=";

    public string GetWeather () {
        string str = "城市名：" + CityName + "；" + "温度：" + TemperatureNow + ";" + "日期：" + Day + ";" + "最高温度：" + TemperatureMax + ";" + "最低温：" + TemperatureMin + ";" + "天气：" + DayWeather + ";" + "风向：" + DayWind + ";" + "风力：" + DayWindLevel + ";" + "夜晚天气：" + NightWeather + ";";
        str += "夜晚风向：" + NightWind + ";" + "夜晚风力：" + NightWindLevel + ";";
        return str;
    }

}